﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Threading;
using System.Configuration;

namespace Comm
{
    /// <summary>
    /// 发送邮件类
    /// </summary>
    public class Email
    {
        public static string smtp = ConfigurationManager.AppSettings["smtp"].ToString();//SMTP服务
        public static string fromemail = ConfigurationManager.AppSettings["fromemail"].ToString();//服务邮箱
        public static string password = ConfigurationManager.AppSettings["password"].ToString();//服务邮箱密码

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="toemail">接受者邮箱</param>
        /// <param name="title">邮件主题</param>
        /// <param name="body">邮件内容</param>
        /// <returns>发送结果</returns>
        public static bool sendEmail(string toemail, string title, string body)
        {
            MailAddress EmailFrom = new MailAddress(fromemail);
            MailAddress EmailTo = new MailAddress(toemail);
            MailMessage Email = new MailMessage(EmailFrom, EmailTo);
            Email.Priority = MailPriority.Normal;
            Email.IsBodyHtml = true;
            Email.Subject = title;
            Email.Body = body;

            SmtpClient Client = new SmtpClient();
            Client.Credentials = new System.Net.NetworkCredential(fromemail, password);
            Client.DeliveryMethod = SmtpDeliveryMethod.Network;

            try
            {
                Client.Send(Email);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }

    /// <summary>
    /// 异步发送邮件类
    /// </summary>
    public class AsEmail
    {
        protected delegate bool SendEmailDelegate(string toemail, string title, string body);
        /// <summary>
        /// 异步发送邮件
        /// </summary>
        /// <param name="toemail">接受者邮箱</param>
        /// <param name="title">邮件主题</param>
        /// <param name="body">邮件内容</param>
        public static void sendAsEmail(string toemail, string title, string body)
        {
            SendEmailDelegate sed = new SendEmailDelegate(Email.sendEmail);
            sed.BeginInvoke(toemail, title, body, null, null);
        }
    }
}
